import datetime

from django.db.models import Q
from six_it.models import Order


def get_house_count_date(house, start_day='', end_day='', result=15):
    if not (start_day or end_day):  # 开始结束时间都没有传入 默认从今天往后result天
        start = datetime.datetime.today()
        end = start + datetime.timedelta(days=result)
        start = datetime.datetime.date(start)
        end = datetime.datetime.date(end)
    elif start_day and not end_day:  # 开始时间传入 默认从今天往后result天
        end = datetime.datetime.strptime(start_day, '%Y-%m-%d') + datetime.timedelta(days=result)
        start = datetime.datetime.date(datetime.datetime.strptime(start_day, '%Y-%m-%d'))
        end = datetime.datetime.date(end)
    elif end_day and not start_day:  # 结束时间传入 默认从今天到结束时间
        start = datetime.datetime.today()
        end = datetime.datetime.date(datetime.datetime.strptime(end_day, '%Y-%m-%d'))
        start = datetime.datetime.date(start)
    else:
        start = datetime.datetime.date(datetime.datetime.strptime(start_day, '%Y-%m-%d'))
        end = datetime.datetime.date(datetime.datetime.strptime(end_day, '%Y-%m-%d'))

    if start > end:  # 判断时间是否逻辑正确
        start, end = end, start

    # 对订单查询
    # 开始时间小于房屋所有订单结束时间
    # 结束时间大于房屋所有订单开始时间
    # 订单状态必须是[2,3,4]
    orders = Order.objects.filter(
        Q(house=house) & Q(begin_date__lte=end) & Q(end_date__gte=start) & Q(status__in=[2, 3, 4])
    )

    # 订单数量初始值
    _ = 0

    for i in range((end - start).days + 1):  # 循环每天进行比较
        day = start + datetime.timedelta(days=i)  # 从开始+i天

        # 由于上面已经筛选一次订单 这里只对时间进行判断 取出订单数量
        count = orders.filter(Q(begin_date__lte=day) & Q(end_date__gte=day)).count()
        _ = max(_, count)

        # 一旦 订单大于等于房间的数量 返回 剩余房间数
        if _ >= house.room_count:
            return 0

    return max(0, house.room_count - _)
